package com.hellobike.haxing.web.user;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.hellobike.haxing.anno.NoAuth;
import com.hellobike.haxing.common.ResponseCodeEnum;
import com.hellobike.haxing.order.result.Result;
import com.hellobike.haxing.user.ILoginService;
import com.hellobike.haxing.user.request.VerificationCodeRequest;
import com.hellobike.haxing.user.vo.UserRegisterVo;
import com.hellobike.haxing.user.vo.UserVo;
import com.hellobike.haxing.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RequestMapping(value = "/login")
@Api(tags = "登录相关的接口")
@RestController
@NoAuth
@Slf4j
public class LoginController {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private UserUtil userUtil;

    @ApiOperation("短信验证码接口")
    @RequestMapping(value = "/verfication", method = {RequestMethod.POST, RequestMethod.GET})
    public Result<String> verficationCode(@ApiParam("验证码请求") @RequestBody VerificationCodeRequest request) {
        if (StringUtils.isEmpty(request.getCode())) {
            request.setCode(RandomUtil.randomString(10));
        }
        if (StringUtils.isEmpty(request.getMobile())) {
            Result<String> result = Result.error(400, "参数异常");
            return result;
        }
        log.info("shop verfication==>{}", JSON.toJSONString(request));
        return loginService.verficationCode(request);
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public Result<UserVo> login(@Valid @RequestBody UserRegisterVo request) {
        request.setPlatform(2);
        Result<UserVo> result = new Result<>();
        if (StringUtils.isEmpty(request.getSmsCode())) {
            result.faild(ResponseCodeEnum.NO_PARAM.code(), "验证码不能为空");
            return result;
        }
        Result<UserVo> userVoResult = loginService.login(request);
        if (userVoResult.getData() != null) {
            userVoResult.setData(userUtil.getUser(userVoResult.getData().getToken()));
            userVoResult.getData().setLogin(true);
        }
        return userVoResult;
    }

}
